package cc.rengu.igas.mcps.core.service.trans.cardpay;

import cc.rengu.igas.channel.cups.common.constant.CupsConfigConstant;
import cc.rengu.igas.channel.cups.facade.bean.CupsTermInfo;
import cc.rengu.igas.channel.cups.facade.bean.OrigTxnInfo;
import cc.rengu.igas.channel.cups.facade.request.PreAuthCancelRequest;
import cc.rengu.igas.channel.cups.facade.response.PreAuthCancelResponse;
import cc.rengu.igas.mcps.common.constant.McpsParamConstant;
import cc.rengu.igas.mcps.common.constant.McpsTreeNodeConstant;
import cc.rengu.igas.mcps.common.enums.McpsAcctTypeEnum;
import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.igas.mcps.core.model.PosTransInfo;
import cc.rengu.igas.mcps.core.realize.PosParamDealService;
import cc.rengu.igas.mcps.core.realize.impl.PosParamDealServiceImpl;
import cc.rengu.igas.mcps.core.service.base.CancelService;
import cc.rengu.igas.mcps.facade.request.PosCardCancelAuthRequest;
import cc.rengu.igas.mcps.facade.response.PosCardCancelAuthResponse;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.model.MchntTermInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * POSC发起的预授权撤销请求
 * Created by zhangbin on 2020/3/31
 */
public class PosCardPreAuthCancelService extends CancelService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        PosCardCancelAuthRequest posCardCancelAuthRequest = new PosCardCancelAuthRequest();
        ConvertUtil.convertOutput(posCardCancelAuthRequest);
        return posCardCancelAuthRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        BizResponse bizResponse = new BizResponse();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        String newPin = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.PIN_DATA);
        PosCardCancelAuthRequest posCardCancelAuthRequest = (PosCardCancelAuthRequest) request;
        PosCardCancelAuthResponse posCardCancelAuthResponse = new PosCardCancelAuthResponse();
        OrderService orderService = new OrderServiceImpl();
        //获取原商户订单
        MchntOrderInfo origMchntOrderInfo = (MchntOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_MCHNT_ORDER_INFO);
        //获取原用户订单
        UserOrderInfo origUserOrderInfo = (UserOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_USER_ORDER_INFO);
        //初始化用户订单表
        UserOrderInfo userOrderInfoCancel = initOrderInfoUser(posCardCancelAuthRequest);
        //初始化商户订单表
        MchntOrderInfo mchntOrderInfoCancel = initOrderInfoMchnt(posCardCancelAuthRequest, userOrderInfoCancel);
        //获取卡BIN信息并判断是否支持此类卡的渠道交易
        /*获取卡号*/
        String cardNo = posCardCancelAuthRequest.getPayAcctNo();
        // 获取实际支付通道
        //获取原ｅｓｂ通道支付订单
        PayOrderInfo oriPayOrderInfoESB = (PayOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_PAY_ORDER_INFO);
        /*创建esb通道支付订单*/
        List<ChannelCallCfg> esbchannelCallCfgList = txnInfo.getChannelCallCfgList().stream().filter(item -> item.getCallChannelId().equals(ChannelEnum.CUPS.getChannelType())).sorted(Comparator.comparing(ChannelCallCfg::getCallIndex)).collect(Collectors.toList());
        ChannelCallCfg channelCallCfg = esbchannelCallCfgList.get(0);
        String refNo = (new PosParamDealServiceImpl()).getRefNo();
        PayOrderInfo payOrderInfoCancel = initPayOrderInfoESB(oriPayOrderInfoESB, posCardCancelAuthRequest, channelCallCfg.getCallIndex(), channelCallCfg.getCallChannelId(), oriPayOrderInfoESB, refNo);
        /*注册登计三张订单*/
        List<MchntOrderInfo> mchntOrderInfoList = new ArrayList<>();
        mchntOrderInfoList.add(mchntOrderInfoCancel);
        if (!orderService.registerOrderInfo(userOrderInfoCancel, mchntOrderInfoList, payOrderInfoCancel)) {
            rglog.error("登记订单失败!");
            throw new BizException(RespCodeEnum.INSERT_ORDER_INFO_ERROR.getRespCode(), RespCodeEnum.INSERT_ORDER_INFO_ERROR.getRespDesc());
        }

        //本行贷记卡调用银数接口
        if (McpsAcctTypeEnum.OWN_CREDIT.getAcctType().equals(oriPayOrderInfoESB.getPayerAcctType())) {
            updcCancel(posCardCancelAuthRequest, origUserOrderInfo, origMchntOrderInfo, oriPayOrderInfoESB, newPin, mchntOrderInfoCancel, userOrderInfoCancel, payOrderInfoCancel);
        }
        //他行卡 调用银联
        if (McpsAcctTypeEnum.OTHER_DEBIT.getAcctType().equals(oriPayOrderInfoESB.getPayerAcctType()) || McpsAcctTypeEnum.OTHER_CREDIT.getAcctType().equals(oriPayOrderInfoESB.getPayerAcctType())) {
            cupsCancel(posCardCancelAuthRequest, origUserOrderInfo, origMchntOrderInfo, oriPayOrderInfoESB, newPin, mchntOrderInfoCancel, userOrderInfoCancel, payOrderInfoCancel, posCardCancelAuthResponse, refNo);
        }

        /* 重组响应结果 */
        ConvertUtil.convertOutput(posCardCancelAuthResponse);
        posCardCancelAuthResponse.setHeader(posCardCancelAuthRequest.getHeader());
        posCardCancelAuthResponse.setPayId(sysSeqNum);
        //posCardCancelAuthResponse.setEpayRrn(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        //bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        //bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setRespCode(payOrderInfoCancel.getRespCode());
        bizResponse.setRespDesc(payOrderInfoCancel.getRespDesc());
        bizResponse.setResult(posCardCancelAuthResponse);
        return bizResponse;

    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        PosCardCancelAuthResponse posCardCancelAuthResponse = (PosCardCancelAuthResponse) bizResponse.getResult();
        posCardCancelAuthResponse.setRespCode(bizResponse.getRespCode());
        posCardCancelAuthResponse.setRespDesc(bizResponse.getRespDesc());
        ConvertUtil.convertInput(posCardCancelAuthResponse);
    }


    /**
     * 登记用户订单表
     *
     * @param posCardCancelAuthRequest 请求信息
     * @throws Exception 异常
     */
    private UserOrderInfo initOrderInfoUser(PosCardCancelAuthRequest posCardCancelAuthRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        UserOrderInfo userOrderInfo = new UserOrderInfo();
        /*获取原用户订单表*/
        UserOrderInfo oriUserOrderInfo = (UserOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_USER_ORDER_INFO);
        /*获取机构号*/
        String instId = posCardCancelAuthRequest.getHeader().getInstId();
        /*获取交易码*/
        String txnNum = posCardCancelAuthRequest.getHeader().getTxnNum();
        /*获取业务细分*/
        String bizType = posCardCancelAuthRequest.getHeader().getBizType();
        /*获取源系统标识*/
        String msgSrcId = posCardCancelAuthRequest.getHeader().getSrcSysId();
        userOrderInfo.setUserOrderId(sysSeqNum);
        userOrderInfo.setMchntOrderId(sysSeqNum);
        userOrderInfo.setInstId(instId);
        userOrderInfo.setTxnDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_DATE));
        userOrderInfo.setTxnTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_TIME));
        userOrderInfo.setTxnNum(txnNum);
        userOrderInfo.setBizType(bizType);
        userOrderInfo.setMsgSrcId(msgSrcId);
        userOrderInfo.setTransChannelId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_CHANNEL_ID));
        userOrderInfo.setFrontSeqNum(posCardCancelAuthRequest.getHeader().getTraceNo());
        userOrderInfo.setSysSeqNum(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));
        userOrderInfo.setOrderCreateTime(DateUtil.getCurrentDateTime("yyyyMMddHHmmss"));
        userOrderInfo.setOrderExpiryTime(DateUtil.getDateByTimeStamp(System.currentTimeMillis() + 5 * 60 * 1000, "yyyyMMddHHmmss"));
        userOrderInfo.setOrderStatus(OrderStatusEnum.INIT.getStatus());
        userOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        userOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        userOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        userOrderInfo.setOrderAmt(oriUserOrderInfo.getOrderAmt());
        userOrderInfo.setOrigTxnDate(oriUserOrderInfo.getTxnDate());
        userOrderInfo.setOrigSysSeqNum(oriUserOrderInfo.getSysSeqNum());
        return userOrderInfo;
    }

    /**
     * 登记商户订单表
     *
     * @param posCardCancelAuthRequest 请求信息
     * @throws Exception 异常
     */
    private MchntOrderInfo initOrderInfoMchnt(PosCardCancelAuthRequest posCardCancelAuthRequest, UserOrderInfo userOrderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        MchntOrderInfo mchntOrderInfo = new MchntOrderInfo();
        /*获取商户基本信息*/
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(posCardCancelAuthRequest.getHeader().getInstId(), posCardCancelAuthRequest.getMchntNo());
        if (null == mchntInfo) {
            rglog.error("查询商户基本信息失败<{}>", posCardCancelAuthRequest.getMchntNo());
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        /*内部树复制会把订单状态保存到商户订单信息表*/
        BeanUtil.beanCopy(userOrderInfo, mchntOrderInfo);
        /*商户订单号*/
        mchntOrderInfo.setMchntOrderId(sysSeqNum);
        /*设置操作员id*/
        mchntOrderInfo.setUserId(posCardCancelAuthRequest.getUserId());
        /*设置商户订单表中业务产品代码*/
        mchntOrderInfo.setBizProdCode(txnInfo.getSrcTxnAuthCfg().getBizProdCode());
        /*收单机构号   从系统参数表中获取value值 即为收单机构号*/
        mchntOrderInfo.setAcqInstCode(mchntInfo.getSignInstId());
        /*行业类别*/
        mchntOrderInfo.setIndustryType(mchntInfo.getIndustryType());
        /*商户号*/
        mchntOrderInfo.setMchntNo(posCardCancelAuthRequest.getMchntNo());
        /*若存在 设置连锁商户门店*/
        if (null != mchntInfo.getChainMchntNo()) {
            mchntOrderInfo.setChainMchntNo(mchntInfo.getChainMchntNo());
        }
        /*商户名称*/
        mchntOrderInfo.setMchntName(mchntInfo.getMchntName());
        /*交易币种*/
        mchntOrderInfo.setOrderCcy(AppParamConstant.DEFAULT_ORDER_CCY);
        /*交易金额*/
        mchntOrderInfo.setRealSettleAmt(userOrderInfo.getOrderAmt());
        /*实时清算标识*/
        mchntOrderInfo.setRealSettleFlag(mchntInfo.getRealSettleFlag());
        /*创建时间*/
        mchntOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        /*初始化订单状态*/
        mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        mchntOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        /*设置终端号*/
        mchntOrderInfo.setTermNo(posCardCancelAuthRequest.getTermNo());
        return mchntOrderInfo;
    }

    /**
     * 登记支付订单表
     *
     * @param posCardCancelAuthRequest 请求信息
     * @throws Exception 异常
     */
    private PayOrderInfo initPayOrderInfoESB(PayOrderInfo origPayOrderInfo, PosCardCancelAuthRequest posCardCancelAuthRequest, String dstCallIndex,
                                             String channelId, PayOrderInfo oriPayOrderInfo, String refNo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /**/
        PosParamDealService posParamDealService = new PosParamDealServiceImpl();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        /* 登记支付订单信息 */
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        String txnNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_NUM);
        String bizType = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.BIZ_TYPE);
        PayOrderInfo payOrderInfo = new PayOrderInfo();
        payOrderInfo.setSysSeqNum(sysSeqNum);
        payOrderInfo.setMchntOrderId(sysSeqNum);
        payOrderInfo.setInstId(instId);
        payOrderInfo.setTxnDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_DATE));
        payOrderInfo.setTxnTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_TIME));
        payOrderInfo.setTxnNum(txnNum);
        payOrderInfo.setBizType(bizType);
        payOrderInfo.setMchntNo(posCardCancelAuthRequest.getMchntNo());
        payOrderInfo.setOrderCcy(AppParamConstant.DEFAULT_ORDER_CCY);
        payOrderInfo.setOrderAmt(origPayOrderInfo.getOrderAmt());
        payOrderInfo.setRealPayAmt(origPayOrderInfo.getRealPayAmt());
        payOrderInfo.setMsgDstId(channelId);
        String strIndex = xmlTreeUtil.getXmlTreeStringValue("currentDstCallIndex");
        Integer acctCallIndex = new Integer((StringUtil.isEmptyOrNull(strIndex)) ? "0" : strIndex);
        String dstAcctCallIndex = Integer.toString(acctCallIndex + 1);
        payOrderInfo.setDstCallIndex(acctCallIndex.toString());
        xmlTreeUtil.setXmlTreeStringValue("currentDstCallIndex", dstAcctCallIndex);
        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        payOrderInfo.setChannelOrderId(sysSeqNum);
        if (McpsAcctTypeEnum.OWN_CREDIT.getAcctType().equals(oriPayOrderInfo.getPayerAcctType())) {
            /*判断本他行卡 设置对账唯一key*/
            payOrderInfo.setChannelReconKey(payOrderInfo.getChannelOrderId());
            /*通道交易码*/
            payOrderInfo.setDstTxnNum("00260000516100");
        } else {
            /*通道类型*/
            payOrderInfo.setDstChannelType(ChannelEnum.CUPS.getChannelType());
            /*他行卡 7域+11域+32域+33域*/
            payOrderInfo.setChannelReconKey(posParamDealService.getCupsReconKey(instId, posCardCancelAuthRequest.getMchntNo()));
            /*支付方式*/
            payOrderInfo.setPayType(PayTypeEnum.OTHER_BANK_CARD.getPayType());
            ChannelCallCfg channelCallCfgList = txnInfo.getChannelCallCfgList().stream().filter(item -> ChannelEnum.CUPS.getChannelType().equals(item.getCallChannelId())).collect(Collectors.toList()).get(0);
            /*通道交易码*/
            payOrderInfo.setDstTxnNum(channelCallCfgList.getCallChannelTxn());
        }
        payOrderInfo.setPayerAcctInfo(posCardCancelAuthRequest.getPayAcctNo());
        payOrderInfo.setPayeeAcctInfo(origPayOrderInfo.getPayeeAcctInfo());
        payOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        payOrderInfo.setPayerAcctType(origPayOrderInfo.getPayerAcctType());
        payOrderInfo.setPayType(oriPayOrderInfo.getPayType());
        payOrderInfo.setOrigSysSeqNum(origPayOrderInfo.getSysSeqNum());
        payOrderInfo.setOrigTxnDate(origPayOrderInfo.getTxnDate());
        payOrderInfo.setTransBatchNo(origPayOrderInfo.getTransBatchNo());
        PosTransInfo posTransInfo = new PosTransInfo();
        BeanUtil.beanCopy(posCardCancelAuthRequest, posTransInfo);
        posTransInfo.setRefNo(refNo);
        posTransInfo.setDeviceType(posCardCancelAuthRequest.getTermInfo().getDeviceType());
        payOrderInfo.setPayerRemark(org.apache.commons.codec.binary.Base64.encodeBase64String(JSONObject.toJSONString(posTransInfo).getBytes()));
        return payOrderInfo;
    }

    /*银数 预授权撤销*/
    private void updcCancel(PosCardCancelAuthRequest posCardCancelAuthRequest, UserOrderInfo origUserOrderInfo, MchntOrderInfo origMchntOrderInfo, PayOrderInfo origPayOrderInfoEsb, String newPin, MchntOrderInfo mchntOrderInfo, UserOrderInfo userOrderInfo, PayOrderInfo payOrderInfoCancelESB) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /**/
        PosParamDealService posParamDealService = new PosParamDealServiceImpl();
        OrderService orderService = new OrderServiceImpl();
        DubboService dubboService = new DubboServiceImpl();
        /*获取商户基本信息*/
        // TODO 调用银数 消费撤销,由项目组实现
        // (1) 失败, 更新订单为失败, 非特殊费率商户发起虚拟账户预授权撤销交易acctDealService.acctAuthCancel,返回失败
        // (2) 交易超时, 更新订单为超时.
        // (3) 交易成功,更新原三张订单表状态为撤销,更新撤销交易支付订单交易成功
    }

    /*银联 预授权撤销*/
    private void cupsCancel(PosCardCancelAuthRequest posCardCancelAuthRequest, UserOrderInfo origUserOrderInfo, MchntOrderInfo origMchntOrderInfo, PayOrderInfo origPayOrderInfoEsb, String newPin, MchntOrderInfo mchntOrderInfo, UserOrderInfo userOrderInfo, PayOrderInfo payOrderInfoCancelESB, PosCardCancelAuthResponse posCardCancelAuthResponse, String refNo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /*获取系统流水号*/
        String sysNum = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.SYS_SEQ_NUM);
        String instId = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.INST_ID);
        OrderService orderService = new OrderServiceImpl();
        DubboService dubboService = new DubboServiceImpl();
        /**/
        PosParamDealService posParamDealService = new PosParamDealServiceImpl();
        /*获取商户基本信息*/
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(instId, posCardCancelAuthRequest.getMchntNo());
        if (null == mchntInfo) {
            rglog.error("查询商户基本信息失败<{}>", posCardCancelAuthRequest.getMchntNo());
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        /*准备请求报文 调起esb接口*/
        PreAuthCancelRequest preAuthCancelRequest = new PreAuthCancelRequest();
        /*设置Header*/
        cc.rengu.igas.channel.cups.facade.base.Header header = new cc.rengu.igas.channel.cups.facade.base.Header();
        BeanUtil.beanCopy(posCardCancelAuthRequest.getHeader(), header);
        header.setVersion("1.0.0");
        header.setTxnNum(payOrderInfoCancelESB.getDstTxnNum());
        header.setTraceNo(payOrderInfoCancelESB.getChannelOrderId());
        preAuthCancelRequest.setHeader(header);
        /*设置银数消费撤销请求报文*/
        CupsTermInfo cupsTermInfo = new CupsTermInfo();
        BeanUtil.beanCopy(posCardCancelAuthRequest.getTermInfo(), cupsTermInfo);
        if (StringUtil.isEmptyOrNull(cupsTermInfo.getDeviceType())) {
            MchntTermInfo mchntTermInfo = mchntService.getMchntTermInfo(instId, posCardCancelAuthRequest.getMchntNo(), posCardCancelAuthRequest.getTermNo());
            cupsTermInfo.setDeviceType(mchntTermInfo.getTermType());
        }
        /*设置原交易信息*/
        OrigTxnInfo origTxnInfo = new OrigTxnInfo();
        origTxnInfo.setOriTxnDate(origPayOrderInfoEsb.getTxnDate());
        origTxnInfo.setOriTraceNo(origPayOrderInfoEsb.getChannelOrderId());
        origTxnInfo.setOriTransDateTime(origPayOrderInfoEsb.getTxnDate().substring(4, 8) + origPayOrderInfoEsb.getTxnTime());
        origTxnInfo.setOriCupsTraceNo(origPayOrderInfoEsb.getSysSeqNum().substring(sysNum.length() - 6, sysNum.length()));
        preAuthCancelRequest.setOrigTxnInfo(origTxnInfo);

        preAuthCancelRequest.setOrderAmt(payOrderInfoCancelESB.getRealPayAmt());
        preAuthCancelRequest.setCupsTraceNo(sysNum.substring(sysNum.length() - 6));
        preAuthCancelRequest.setTransDateTime(payOrderInfoCancelESB.getTxnDate().substring(4, 8) + payOrderInfoCancelESB.getTxnTime());
        preAuthCancelRequest.setCupsMchntNo(mchntInfo.getCupsMchntNo());
        preAuthCancelRequest.setMchntNo(preAuthCancelRequest.getMchntNo());
        preAuthCancelRequest.setTermNo(posCardCancelAuthRequest.getTermNo());
        preAuthCancelRequest.setMchntShortName(mchntInfo.getMchntSimpleName());
        preAuthCancelRequest.setMchntType(mchntInfo.getIndustryType());
        preAuthCancelRequest.setAuthCode(origPayOrderInfoEsb.getTxnAuthCode());
        payOrderInfoCancelESB.setTxnAuthCode(origPayOrderInfoEsb.getTxnAuthCode());
        String acqInstCode = posParamDealService.genCupsAcqInstCode(instId, posCardCancelAuthRequest.getMchntNo());
        String fwdInstCode = XmlConfigUtil.getXmlConfigCacheKeyValue(CupsConfigConstant.CUPS_CONF_NODE, CupsConfigConstant.CUPS_FWD_INS_CODE);
        preAuthCancelRequest.setCupsInstCode(acqInstCode);
        preAuthCancelRequest.setFwdInstCode(fwdInstCode);
        preAuthCancelRequest.setOrderCcy(McpsParamConstant.INNER_DEFAULT_ORDERCCY);
        preAuthCancelRequest.setPayAcctNo(posCardCancelAuthRequest.getPayAcctNo());
        //TODO 待修改
        preAuthCancelRequest.setTrack2Data(posCardCancelAuthRequest.getTrack2Data());
        preAuthCancelRequest.setTrack3Data(posCardCancelAuthRequest.getTrack3Data());
        preAuthCancelRequest.setReferenceNo(refNo);
        preAuthCancelRequest.setEntryMode(posCardCancelAuthRequest.getEntryMode());
        preAuthCancelRequest.setCardSeqNo(posCardCancelAuthRequest.getCardSeqNo());
        preAuthCancelRequest.setIcData(posCardCancelAuthRequest.getIcData());
        preAuthCancelRequest.setIcConCode(posCardCancelAuthRequest.getIcConCode());
        preAuthCancelRequest.setTermInfo(cupsTermInfo);
        preAuthCancelRequest.setOrigTxnInfo(origTxnInfo);
        //preAuthCancelRequest.setPinCapCode(posCardCancelAuthRequest.getEntryMode());
        preAuthCancelRequest.setPinData(newPin);
        preAuthCancelRequest.setTermRead(posCardCancelAuthRequest.getTermRead());
        /*打印报文*/
        rglog.info("银联请求报文preAuthCancelRequest：<{}>", JSON.toJSONString(preAuthCancelRequest));
        cc.rengu.igas.channel.cups.facade.result.Result<PreAuthCancelResponse> result = (cc.rengu.igas.channel.cups.facade.result.Result) dubboService.callDubboService("cupsPayService", "preAuthCancel", preAuthCancelRequest);
        rglog.debug("dubbo调用预授权撤销结果：{}", JSON.toJSONString(result));
        /*撤销失败处理*/
        if (null == result || null == result.getResult() || (!result.getResult().getRespCode().equals(McpsParamConstant.DUBBO_SUCCESS) && !result.getResult().getRespCode().equals(McpsParamConstant.DUBBO_OVERTIME) && !McpsParamConstant.COMMUNICATION_OVERTIME.equals(result.getResult().getRespCode()))) {
            payOrderInfoCancelESB.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            payOrderInfoCancelESB.setBizStatus(BizStatusEnum.FAILED.getStatus());
            mchntOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            mchntOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
            userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
            if (!orderService.updateOrderInfo(userOrderInfo, Arrays.asList(mchntOrderInfo), payOrderInfoCancelESB)) {
                rglog.error("订单表更新失败");
                throw new BizException(RespCodeEnum.UPDATE_ORDER_ERROR.getRespCode(), RespCodeEnum.UPDATE_ORDER_ERROR.getRespDesc());
            }
            /*设置返回码 返回信息*/
            if (null == result || !result.isSuccess()) {
                payOrderInfoCancelESB.setRespCode(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                payOrderInfoCancelESB.setRespDesc(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
            } else {
                payOrderInfoCancelESB.setRespCode(result.getResult().getRespCode());
                payOrderInfoCancelESB.setRespDesc(result.getResult().getRespDesc());
            }
        }
        //撤销超时处理
        /*判断是否超时*/
        else if (result.isSuccess() && (McpsParamConstant.DUBBO_OVERTIME.equals(result.getResult().getRespCode()) || McpsParamConstant.COMMUNICATION_OVERTIME.equals(result.getResult().getRespCode()))) {
            //更新撤销订单状态为失败,并更新原交易系统流水号、交易日期
            payOrderInfoCancelESB.setRespCode(result.getResult().getRespCode());
            payOrderInfoCancelESB.setRespDesc(result.getResult().getRespDesc());
            payOrderInfoCancelESB.setTransStatus(TransStatusEnum.TRANS_TIMEOUT.getStatus());
            //更新商户订单状态为失败，并更新原交易系统流水号、交易日期
            mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_TIMEOUT.getStatus());
            List<MchntOrderInfo> listMchntOrderInfo = new ArrayList<>();
            listMchntOrderInfo.add(mchntOrderInfo);
            //更新用户订单状态为失败，并更新原交易系统流水号、交易日期
            userOrderInfo.setTransStatus(TransStatusEnum.TRANS_TIMEOUT.getStatus());
            if (!orderService.updateOrderInfo(userOrderInfo, listMchntOrderInfo, payOrderInfoCancelESB)) {
                rglog.error("订单表更新失败");
                throw new BizException(RespCodeEnum.UPDATE_ORDER_ERROR.getRespCode(), RespCodeEnum.UPDATE_ORDER_ERROR.getRespDesc());
            }
        }
        //撤销成功处理
        else {
            /*更新原三张订单表状态 为 撤销*/
            origMchntOrderInfo.setBizStatus(BizStatusEnum.CANCEL.getStatus());
            origPayOrderInfoEsb.setBizStatus(BizStatusEnum.CANCEL.getStatus());
            origUserOrderInfo.setBizStatus(BizStatusEnum.CANCEL.getStatus());
            List<MchntOrderInfo> origListMchntOrderInfo = new ArrayList<>();
            origListMchntOrderInfo.add(origMchntOrderInfo);
            if (!orderService.updateOrderInfo(origUserOrderInfo, origListMchntOrderInfo, origPayOrderInfoEsb)) {
                rglog.error("订单表更新失败");
                throw new BizException(RespCodeEnum.UPDATE_ORDER_ERROR.getRespCode(), RespCodeEnum.UPDATE_ORDER_ERROR.getRespDesc());
            }
            //更新撤销交易支付订单交易成功
            payOrderInfoCancelESB.setRespCode(result.getResult().getRespCode());
            payOrderInfoCancelESB.setRespDesc(result.getResult().getRespDesc());
            payOrderInfoCancelESB.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            payOrderInfoCancelESB.setBizStatus(BizStatusEnum.FINISH.getStatus());
            payOrderInfoCancelESB.setSettleDate(result.getResult().getSettleDate());
            //更新撤销交易商户订单交易成功
            mchntOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
            mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            List<MchntOrderInfo> listMchntOrderInfo = new ArrayList<>();
            listMchntOrderInfo.add(mchntOrderInfo);
            //更新撤销交易用户订单交易成功
            userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
            userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            if (!orderService.updateOrderInfo(userOrderInfo, listMchntOrderInfo, payOrderInfoCancelESB)) {
                rglog.error("订单表更新失败");
                throw new BizException(RespCodeEnum.UPDATE_ORDER_ERROR.getRespCode(), RespCodeEnum.UPDATE_ORDER_ERROR.getRespDesc());
            }
        }
        /*设置返回码 返回信息*/
        if (null == result || !result.isSuccess()) {
            posCardCancelAuthResponse.setRespCode(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
            posCardCancelAuthResponse.setRespDesc(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
        } else {
            posCardCancelAuthResponse.setRespCode(result.getResult().getRespCode());
            posCardCancelAuthResponse.setRespDesc(result.getResult().getRespDesc());
            posCardCancelAuthResponse.setPayId(sysNum);
            posCardCancelAuthResponse.setSettleDate(result.getResult().getSettleDate());
            posCardCancelAuthResponse.setReferenceNo(preAuthCancelRequest.getReferenceNo());
            //收单机构
            posCardCancelAuthResponse.setAcqInstCode(preAuthCancelRequest.getCupsInstCode());
            //发卡机构
            posCardCancelAuthResponse.setPayAcctIssCode(result.getResult().getRcvInstCode());
            posCardCancelAuthResponse.setTxnDate(preAuthCancelRequest.getHeader().getTransDate());
            posCardCancelAuthResponse.setTxnTime(preAuthCancelRequest.getHeader().getTransTime());
        }

    }
}